package com.plian.system.service.hr.employment.impl;

import com.plian.system.dto.hr.employment.EnterpriseEmploymentDTO;
import com.plian.system.entity.hr.employment.EnterpriseEmployment;
import com.plian.system.mapper.hr.employment.EnterpriseEmploymentMapper;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.service.hr.employment.IEnterpriseEmploymentService;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.service.sys.message.IApprovalMessageService;
import com.plian.system.service.sys.orgzation.IOrgService;
import com.plian.system.vo.hr.employment.EnterpriseEmploymentVO;
import com.plian.system.vo.report.HeaderVO;
import com.plian.system.vo.report.ReportReturnVO;
import com.plian.system.vo.report.ReportVO;
import com.plian.system.wrapper.hr.employment.EnterpriseEmploymentWrapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 企业用工管理主表 服务实现类
 *
 * @author gangan
 * @since 2019-11-13
 */
@Service
@AllArgsConstructor
public class EnterpriseEmploymentServiceImpl extends BaseServiceImpl<EnterpriseEmploymentMapper, EnterpriseEmployment> implements IEnterpriseEmploymentService
//		, BaseFlowService
{

    private IFormCodeService formCodeService;

    private EnterpriseEmploymentWrapper enterpriseEmploymentWrapper;

    private IOrgService orgService;


	private IApprovalMessageService approvalMessageService;

//    @Override
//	@Transactional(rollbackFor=RuntimeException.class) TODO DEL
//    public boolean saveOrUpdate(EnterpriseEmployment enterpriseEmployment) {
//		if(enterpriseEmployment.getStatus()==null){
//			enterpriseEmployment.setStatus(FormStatusConstant.UNREVIEWED);
//		}
//		if (enterpriseEmployment.getId() == null){
//			enterpriseEmployment.setCode(formCodeService.getCode(FormTypeConstant.HR_EMPLOYMENT_FORM));
//			enterpriseEmployment.setFormType(String.valueOf(FormTypeConstant.HR_EMPLOYMENT_FORM));
//			enterpriseEmployment.setVersion("1");
//		}
//        return super.saveOrUpdate(enterpriseEmployment);
//    }
//
//    @Override
//    public boolean deleteLogic(List<Long> ids) {
//    for (Long id : ids) {
//        EnterpriseEmployment enterpriseEmployment = getById(id);
//        if (enterpriseEmployment == null) {
//            return false;
//        } else if (enterpriseEmployment.getStatus() != null &&
//				(enterpriseEmployment.getStatus() != FormStatusConstant.STASH && enterpriseEmployment.getStatus() != FormStatusConstant.UNREVIEWED)) {
//			return false;
//		}
//    }
//    return super.deleteLogic(ids);
//    }
//
//    @Override
//    public HashMap<String,Object> commit(String id) {
//        handleStatus(Long.valueOf(id), FormStatusConstant.FLOW,null);
//
//		//将需要提交的流程变量返回，用于工作流侧
//		return new HashMap<String,Object>();
//    }
//
//    @Override
//    public Boolean finish(String id) {
//        return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH,"同意");
//    }
//
//    @Override
//    public Boolean reject(String id, int formState, String comment) {
//		return handleStatus(Long.valueOf(id), formState, comment);
//    }
//
//    /**
//     * 统一处理状态机事件方法
//     * @param id 主键
//     * @param updateStatus 更新状态
//     * @return boolean
//     */
//    private Boolean handleStatus(Long id,int updateStatus,String comment) {
//        try {
//            EnterpriseEmployment enterpriseEmployment = getById(id);
//			/**
//			 * 设置审批人和审批时间
//			 */
//			if (updateStatus == FormStatusConstant.FINISH){
//				enterpriseEmployment.setApprovedUser(TokenUtil.getTokenUserId());
//				Date now = DateUtil.now();
//				enterpriseEmployment.setApprovedTime(now);
//			}
//			if (StringUtil.isNotBlank(enterpriseEmployment.getDataSource()) &&
//					StringUtil.isNotBlank(enterpriseEmployment.getDataSourceId())){
//				if (updateStatus == FormStatusConstant.FINISH || updateStatus == FormStatusConstant.REJECT){
//					ApprovalMessage approvalMessage = new ApprovalMessage();
//					approvalMessage.setDataSourceId(enterpriseEmployment.getDataSourceId());
//					approvalMessage.setOpinion(comment);
//					approvalMessage.setIsApprove(updateStatus == FormStatusConstant.FINISH ? 2 : 1);
//					approvalMessage.setIsSend(1);
//					approvalMessage.setDataSourceType(GZW_TYPE);
//
//					if (enterpriseEmployment.getDataSource().equals(YthConstant.DATA_NINGBO)) {
//						approvalMessage.setDataSourceType(YthConstant.DATA_NINGBO);
//						approvalMessage.setFilingUserName(UserCache.userIdToName(TokenUtil.getTokenUserId()));
//						approvalMessage.setFormType(FormTypeConstant.HR_EMPLOYMENT_FORM);
//					}
//					approvalMessageService.save(approvalMessage);
//				}
//			}
//
//            enterpriseEmployment.setStatus(updateStatus);
//            updateById(enterpriseEmployment);
//            return true;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//            return false;
//        }
//    }

	@Override
	public ReportReturnVO report(EnterpriseEmploymentDTO enterpriseEmploymentDTO){
		ReportReturnVO reportReturnVO = new ReportReturnVO();
		ReportVO reportVO = new ReportVO();

		reportVO
			.addHeader(HeaderVO.builder().key("companyName").title("单位名称").build())
			.addHeader(HeaderVO.builder().key("departmentName").title("部门").build())
			.addHeader(HeaderVO.builder().key("operatingPost").title("工作岗位").build())
			.addHeader(HeaderVO.builder().key("numberOfPeople").title("人数").build())
			.addHeader(HeaderVO.builder().key("educationalName").title("学历").build())
			.addHeader(HeaderVO.builder().key("major").title("专业").build())
			.addHeader(HeaderVO.builder().key("isIncreasingCapital").title("是否属于增人增资范畴").build())
			.addHeader(HeaderVO.builder().key("isIncreasingWorker").title("是否属于补员").build())
			.addHeader(HeaderVO.builder().key("actualWorkersNumber").title("实际用工人数").build())
			.addHeader(HeaderVO.builder().key("remark").title("备注").build());

		//给所有查询出的记录附加企业code编号用于排序,转换名称
		List<EnterpriseEmploymentVO> list = enterpriseEmploymentWrapper.entityToVO(
				baseMapper.reportDataPage(enterpriseEmploymentDTO.getCompanyNameIds(), enterpriseEmploymentDTO.getDepartmentNameId(),
						enterpriseEmploymentDTO.getOperatingPost(), enterpriseEmploymentDTO.getEducationalIds(), enterpriseEmploymentDTO.getMajor(),
						enterpriseEmploymentDTO.getStartYear(), enterpriseEmploymentDTO.getEndYear()));



		//Comparator.comparing(RecruitmentManagementVO::getCompanyCode).reversed() 为降序
		list = list.parallelStream().sorted(Comparator.comparing(EnterpriseEmploymentVO::getCompanyCode).thenComparing(EnterpriseEmploymentVO::getDepartmentCode)).collect(Collectors.toList());

		List<EnterpriseEmploymentVO> list2 = new ArrayList<>() ;
		String companyNameSearchId = "";

		//总计临时变量
		int actualSum = 0;
		int needSum = 0;
		//小计临时变量
		int actualTempSum = 0;
		int needTempSum = 0;
		for(int i =0;i< list.size();i++){
			if(!companyNameSearchId.equals(list.get(i).getCompanyNameId())){
				if(i>0){
					EnterpriseEmploymentVO smallTotal = new EnterpriseEmploymentVO();
					smallTotal.setCompanyName("小计");
					smallTotal.setNumberOfPeople(needTempSum);
					smallTotal.setActualWorkersNumber(actualTempSum);
					list2.add(smallTotal);

					actualSum += actualTempSum;
					needSum += needTempSum;

				}
				companyNameSearchId = list.get(i).getCompanyNameId();
				needTempSum = list.get(i).getNumberOfPeople();
				actualTempSum = list.get(i).getActualWorkersNumber();
			}else{
				needTempSum += list.get(i).getNumberOfPeople();
				actualTempSum += list.get(i).getActualWorkersNumber();
			}
			list2.add(list.get(i));
		}
		EnterpriseEmploymentVO smallTotal = new EnterpriseEmploymentVO();
		smallTotal.setCompanyName("小计");
		smallTotal.setNumberOfPeople(needTempSum);
		smallTotal.setActualWorkersNumber(actualTempSum);
		list2.add(smallTotal);

		actualSum += actualTempSum;
		needSum += needTempSum;

		EnterpriseEmploymentVO total = new EnterpriseEmploymentVO();
		total.setCompanyName("总计");
		total.setNumberOfPeople(needSum);
		total.setActualWorkersNumber(actualSum);

		list2.add(total);

		reportVO.setData(list2);
		reportReturnVO.setGrids(reportVO);
		return reportReturnVO;
	}

//	@Override
//	public List<PageData> findByIds(List<String> formIds) {
//		LambdaQueryWrapper<EnterpriseEmployment> queryWrapper = new LambdaQueryWrapper<>();
//		queryWrapper.in(EnterpriseEmployment::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
//		List<EnterpriseEmployment> enterpriseEmployments = list(queryWrapper);
//		List<EnterpriseEmploymentVO> enterpriseEmploymentVOS = enterpriseEmploymentWrapper.entityToVO(enterpriseEmployments);
//		List<PageData> pageDataList = new ArrayList<>();
//		try{
//			if (CollectionUtil.isNotEmpty(enterpriseEmploymentVOS)){
//				for (EnterpriseEmploymentVO vo : enterpriseEmploymentVOS){
//					PageData pd = new PageData();
//					pd.put("id", vo.getId());
//					pd.put("UNITNAME", vo.getCompanyName());
//					pd.put("APPLICANTNAME", vo.getCreateUserName());
//					pd.put("applicantId", vo.getCreateUser());
//					pd.put("applyOrganizationId", vo.getCompanyNameId());
//					pd.put("formType", FormTypeConstant.HR_EMPLOYMENT_FORM);
//					pd.put("orgName", vo.getCompanyName());
//					pageDataList.add(pd);
//				}
//			}
//
//			return pageDataList;
//		} catch (Exception e) {
//			log.error(ExceptionUtils.getFullStackTrace(e));
//		}
//		return pageDataList;
//	}
//
//	@Override
//	public List<Integer> getFormType() {
//		return Arrays.asList(FormTypeConstant.HR_EMPLOYMENT_FORM);
//	}
//
//	@Override
//	public void goBackToStash(String formId) {
//		handleStatus(Long.valueOf(formId), UNREVIEWED, null);
//	}
//
//	@Override
//	@Transactional(rollbackFor = RuntimeException.class)
//	public String saveEmploymentList(String data){
//		YthResult ythResult = new YthResult();
//		//成功的id集合
//		List<String> successIds = new ArrayList<>();
//		//失败的id集合
//		List<String> failIds = new ArrayList<>();
//		//失败的原因
//		List<String> failReasons = new ArrayList<>();
//		//将json字符串转换成list
//		List<EnterpriseEmployment> dataList = JSON.parseArray(data, EnterpriseEmployment.class);
//		if (CollectionUtil.isNotEmpty(dataList)){
//			Map<String, String> orgSourceMap = orgService.getSourceId();
//			//根据datasourceIds 查询出所有的数据
//			List<EnterpriseEmployment> list = list(new LambdaQueryWrapper<EnterpriseEmployment>().in(EnterpriseEmployment::getDataSourceId, dataList.stream().map(EnterpriseEmployment::getDataSourceId).toArray()));
//			//如果数据库中有数据，就更新，没有就新增
//			for (EnterpriseEmployment entity:dataList){
//				transfer(entity,orgSourceMap);
//				//id重复略过
//				if (CollectionUtil.isNotEmpty(list)){
//					List<String> olIds = list.stream().map(EnterpriseEmployment::getDataSourceId).collect(Collectors.toList());
//					String dataSourceId = entity.getDataSourceId();
//					//判断数据库中是否有数据
//					if (olIds.contains(dataSourceId)){
//						for (EnterpriseEmployment oldEntity:list){
//							if (dataSourceId.equals(oldEntity.getDataSourceId())){
//								//判断status是否为0，如果是0，就更新，不是0，就不更新
//								if (CheckStatus.checkCode(oldEntity.getStatus())){
//									successIds.add(dataSourceId);
//									entity.setId(oldEntity.getId());
//									entity.setDataSource(YthConstant.DATA_NINGBO);
//									saveOrUpdate(entity);
//									list.remove(oldEntity);
//									break;
//								}else {
//									failIds.add(dataSourceId);
//									failReasons.add("dataSourceId:"+dataSourceId+"数据已提交且已经在流程中，无法更新");
//									break;
//								}
//							}
//						}
//					}else {
//						//如果数据库中没有数据，就新增
//						entity.setDataSource(YthConstant.DATA_NINGBO);
//						saveOrUpdate(entity);
//						successIds.add(entity.getDataSourceId());
//					}
//				}else {
//					//如果数据库中没有数据，就新增
//					entity.setDataSource(YthConstant.DATA_NINGBO);
//					saveOrUpdate(entity);
//					successIds.add(entity.getDataSourceId());
//				}
//			}
//		} else {
//			failReasons.add("数据为空");
//		}
//		ythResult.setSuccessIds(successIds);
//		ythResult.setFailIds(failIds);
//		ythResult.setFailReason(StringUtils.join(failReasons, ";"));
//		//ythResult转换成json字符串
//		return JSON.toJSONString(ythResult);
//	}
//
//	private void transfer(EnterpriseEmployment entity, Map<String, String> orgSourceMap){
//		Optional.ofNullable(entity.getCompanyNameId()).ifPresent(m ->
//				{
//					String orgId = orgSourceMap.get(m);
//					entity.setCompanyNameId(orgId);
//				}
//		);
//
//		Optional.ofNullable(entity.getFillingUnitId()).ifPresent(m ->
//				{
//					String orgId = orgSourceMap.get(m);
//					entity.setFillingUnitId(orgId);
//					entity.setCreateCompanyId(orgId);
//				}
//		);
//
//	}
}
